import { useState, CSSProperties } from "react";
import clsx from "classnames";

import { CommonComponentProps, CommonComponentResult, Key } from "./type";

export function useComponent(
  props: CommonComponentProps & {
    wrapperCls?: string;
    wrapperStyle?: CSSProperties;
    [unknownKey: string]: any;
  }
): CommonComponentResult {
  const { className, wrapperCls, style, wrapperStyle, onChange, value, defaultValue } = props;

  const isControlled = typeof value !== "undefined";
  const initialVal = isControlled ? value : defaultValue ?? null;

  const [innerValue, setInnerValue] = useState<Key>(initialVal);

  const computedVal = isControlled ? value : innerValue;

  const resolveChange = (v: Key) => {
    onChange?.(v);
    if (!isControlled) {
      setInnerValue(v);
    }
  };

  const finalCls = clsx(wrapperCls, className);
  const finalStyle = {
    ...style,
    ...wrapperStyle,
  };

  return {
    val: computedVal,
    action: resolveChange,
    className: finalCls,
    style: finalStyle,
  };
}
